<template>
  <div class="tao-table" :class="{ 'hide-scroll-bar': hideScrollBar }">
    <el-table
      ref="table"
      row-key="id"
      :data="data || tableData"
      :height="height"
      :row-class-name="tableRowClassName"
      :cell-style="tableCellClassName"
      :header-cell-style="{ background: headBg, color: '#333' }"
      :fit="true"
      :size="size"
      :style="{ marginBottom: Bottom + 'px' }"
      style="width: 100%; font-size: 20px"
      tooltip-effect="dark"
      @selection-change="handleSelectionChange"
      border
      highlight-current-row
      @cell-dblclick="clickHandler"
      @sort-change="sortHandler"
      :summary-method="getSummaries"
      :show-summary="isSummary"
    >
      <el-table-column
        type="selection"
        v-if="isSelection && data.length > 0 ? true : false"
        fixed="left"
        width="55"
        alige="center"
      >
      </el-table-column>
      <el-table-column label="序号" v-if="isOrder" align="center">
        <template slot-scope="scope">
          <span>
            {{
              scope.$index + (pageData.current_page - 1) * pageData.per_page + 1
            }}
          </span>
        </template>
      </el-table-column>
      <!-- 插槽 -->
      <slot></slot>

      <!-- 筛选 -->
      <el-table-column
        v-if="status"
        :prop="statusProp"
        :label="statusTitle"
        :width="isStatus ? '90' : ''"
        :filters="[
          { text: '已启用', value: 1 },
          { text: '已禁用', value: 0 }
        ]"
        :filter-method="filterTag"
        filter-placement="bottom-end"
      >
        <template slot-scope="scope">
          <el-tag
            size="mini"
            effect="light"
            :type="scope.row[statusProp] === 1 ? 'success' : 'info'"
            disable-transitions
          >
            {{ scope.row[statusProp] === 1 ? "已启用" : "已禁用" }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 没有数据 -->
      <div slot="empty" class="empty" style="padding: 20px 0">
        <div v-if="showEmptyTips">
          <i class="iconfont">&#xe707;</i>
          <p>{{ emptyText }}</p>
        </div>
      </div>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      :page-size="page.pageSize"
      :total="page.total"
      :page-sizes="[10, 20, 30, 40, 50, 60, 70, 80]"
      :current-page.sync="page.page"
      @current-change="changePage"
      @size-change="changeSize"
      :layout="pageLaout"
      :hide-on-single-page="hideOnePage"
      v-if="showPage && page.total > 0"
    />
  </div>
</template>

<script>
export default {
  name: "KTable",
  props: {
    data: Array,
    page: {
      type: Object,
      default: function() {
        return {
          page: 1,
          pageSize: 30,
          total: 0
        };
      }
    },
    defaultData: Boolean,
    statusTitle: {
      type: String,
      default: "状态"
    },
    status: {
      type: Boolean,
      default: false
    },
    statusProp: {
      type: String,
      default: "status"
    },
    height: {
      type: String
    },
    isLimit: {
      type: Boolean,
      default: true
    },
    emptyText: {
      type: String,
      default: "暂无数据"
    },
    hideOnePage: {
      type: Boolean,
      default: false
    },
    pageLaout: {
      type: String,
      default: "total, prev, pager, next, jumper"
    },
    Bottom: {
      type: Number,
      default: 0
    },
    showPage: {
      type: Boolean,
      default: true
    },
    isSummary: {
      type: Boolean,
      default: false
    },
    isStatus: {
      type: Boolean,
      default: true
    },
    isOrder: {
      type: Boolean,
      default: false
    },
    hideScrollBar: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: "medium"
    },
    headBg: {
      type: String,
      default: "#f5f7fa"
    },
    isSelection: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tableData: [],
      multipleSelection: [],
      pageData: {
        total: 1000,
        current_page: 1,
        per_page: 100,
        last_page: 1
      },
      showEmptyTips: false
    };
  },
  updated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout();
    });
  },
  mounted() {
    if (!this.data) {
      this.setDefaultData();
    }

    this.setEmptyTips();
  },
  methods: {
    setDefaultData() {
      let arr = [];

      for (let i = 0; i < 25; i++) {
        arr.push({
          id: i + 1,
          default: "默认值"
        });
      }

      this.tableData = arr;
    },
    // 点击分页按钮
    changePage(page) {
      this.$emit("changePage", { page });
    },
    // 改变每页显示记录数
    changeSize(limit) {
      if (this.isLimit) {
        this.pageSizeStore(limit);
      }
      this.$emit("changePage", { limit });
    },
    // 每一页pageSize持久化
    pageSizeStore(limit) {
      // this.$store.dispatch('worktab/setPageSize', { limit })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    filterTag(value, row) {
      return row[this.statusProp] === value;
    },
    setEmptyTips() {
      setTimeout(() => {
        this.showEmptyTips = true;
      }, 300);
    },
    // 表格间隔class
    tableRowClassName({ row, rowIndex }) {
      if (row.xsprice < 0) {
        return "negative";
      } else if (row.ckamount < 0) {
        return "negative";
      } else {
        return "";
      }
    },
    tableCellClassName({ row, column, rowIndex, columnIndex }) {
      if (
        column.label === "销售价" ||
        column.label === "日销售额" ||
        column.label === "订单金额" ||
        column.label === "实付金额"
      ) {
        return "color:#FF0000";
      }
      if (column.label === "绑定客户") {
        return "color:#2D8CF0";
      }
      return "";
    },
    clickHandler(val) {
      this.$emit("clickHandler", val);
    },
    // 单击
    rowClick(row) {
      this.$emit("rowClick", row);
      this.setSelectedIndex(row);
      // //如果选中，自动取消选中
      if (this.multipleSelection && this.multipleSelection.length > 0) {
        for (let index = 0; index < this.multipleSelection.length; index++) {
          const element = this.multipleSelection[index];
          if (element.ckpaper === row.ckpaper) {
            this.$nextTick(() => {
              this.$refs.table.toggleRowSelection(element, false);
            });
            break;
          }
        }
      }
    },
    //当前选中行
    setSelectedIndex(row) {
      for (let index = 0; index < this.data.length; index++) {
        const element = this.data[index];
        if (element.ckpaper === row.ckpaper) {
          this.$nextTick(() => {
            this.$refs.table.toggleRowSelection(row);
          });
          break;
        }
      }
    },
    sortHandler(val) {
      this.$emit("sortHandler", val);
    },
    doLayout() {
      this.$nextTick(() => {
        this.$refs.table.doLayout();
      });
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        if (column.property === "ddnote") {
          sums[index] = "";
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (column.property === "xsprice") {
            sums[index] = parseFloat(sums[index]).toFixed(2);
          } else {
            sums[index] = sums[index];
          }
        } else {
          sums[index] = "";
        }
      });
      return sums;
    }
  },
  watch: {
    data: {
      handler(newVal, oldVal) {
        this.$nextTick(() => {
          this.$refs.table.doLayout();
        });
        // 设置默认勾选
        for (let index = 0; index < newVal.length; index++) {
          const element = newVal[index];
          if (element.是否打印 !== "已打印") {
            this.$nextTick(() => {
              this.$refs.table.toggleRowSelection(element);
            });
          }
        }
      },
      immediate: true,
      deep: true
    },
    page: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.pageData = newVal;
        }
      },
      immediate: true,
      deep: true
    },
    multipleSelection: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.$emit("selectData", newVal);
          // console.log(newVal);
        }
      },
      immediate: true,
      deep: true
    }
  }
};
</script>

<style lang="scss" scoped>
.tao-table {
  // height: 100% !important;

  // 分页组件
  ::v-deep .el-pagination {
    margin: 20px 0 0 -5px;
    padding-left: 0;
  }

  // 滚动条
  ::v-deep ::-webkit-scrollbar {
    height: 6px !important;
    display: block !important;
  }

  .empty {
    i {
      color: #d7d6d6;
      font-size: 40px;
    }

    p {
      color: #999999;
      font-size: 13px;
      line-height: 30px;
      margin-top: -10px;
    }
  }
}

.hide-scroll-bar {
  ::v-deep ::-webkit-scrollbar {
    width: 0 !important;
    height: 0 !important;
  }
}
</style>
